package io;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件操作工具类
 * 提供图片下载、目录创建、日志记录等功能
 */

public class FileUtils {
    //从URL下载图片并保存到指定路径
    //@param url 图片的URL地址
    //@param savePath 保存路径
    //@throws IOException 当网络连接或文件操作失败时抛出异常

    public static void saveImage(String url,String savePath)throws IOException {
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        FileOutputStream outputStream = null;

        try {
            // 创建URL对象
            URL imageUrl = new URL(url);
            connection = (HttpURLConnection) imageUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000); // 10秒连接超时
            connection.setReadTimeout(30000);    // 30秒读取超时

            // 检查HTTP响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("HTTP error code: " + responseCode);
            }

            //获取输入流和输出流
            inputStream = connection.getInputStream();
            outputStream = new FileOutputStream(savePath);

            //缓冲区
            byte[] buffer = new byte[4096];
            int bytesRead;
            while((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            System.out.println("图片下载成功：" + savePath);
        }finally {
            //关闭资源
            if(inputStream != null){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try{
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if(connection != null){
                connection.disconnect();
            }
        }
    }

    //创建目录
    public static void ensureDirectoryExists(String dirPath){
        File directory = new File(dirPath);
        if(!directory.exists()){
            if(directory.mkdir()){
                System.out.println("目录创建成功：" + dirPath);
            }else{
                System.out.println("目录创建失败："+dirPath);
            }
        }
    }

    //将下载记录追加到日志文件中
    public static void appendlog(String log){
        try(FileWriter writer = new FileWriter("download_log.txt",true)) {
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String logEntry = timestamp + " " + log + "\n";
            writer.write(logEntry);
        }catch (IOException e){
            System.out.println("日志记录失败：" + e.getMessage());
        }
    }
}
